package com.example.registration.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;

import androidx.core.app.ActivityCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * desc: 检查并申请权限
 * use:
 */
public class PermissionHelper {

    private Context context;
    private PermissionCallback callback;

    public interface PermissionCallback {
        void onPermissionGranted();
        void onPermissionDenied(List<String> deniedPermissions);
    }

    // 检查是否有权限
    public static boolean hasPermission(Context context, String permission) {
        return ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
    }

    //动态申请权限
    public static void requestPermissions(Activity activity, String[] permissions, int requestCode, PermissionCallback callback) {
        if (activity == null || permissions == null || permissions.length == 0) {
            return;
        }

        List<String> deniedPermissions = new ArrayList<>();

        // 先检查权限，只请求那些未被授予的权限
        for (String permission : permissions) {
            if (!hasPermission(activity, permission)) {
                deniedPermissions.add(permission);
            }
        }

        // 如果没有任何权限被拒绝，则直接回调权限已授予
        if (deniedPermissions.isEmpty()) {
            if (callback != null) {
                callback.onPermissionGranted();
            }
            return;
        }

        // 请求权限
        ActivityCompat.requestPermissions(activity, deniedPermissions.toArray(new String[0]), requestCode);
    }

}